import { api } from './api.config'

// 登录
export const login = (data) => {
    //jwtToken 和 请求类型已做全局拦截添加
    return api({
        url: "/api/login",
        method: "post",
        data
    })
}
// 注册
export const register = (data) => {
    //jwtToken 和 请求类型已做全局拦截添加
    return api({
        url: "/api/register",
        method: "post",
        data
    })
}

//获取下发人员
export const getUsername = (params) => {
    return api({
        url: "/api/getUsername",
        method: "get",
        params,
    })
}


// 任务派发
export const taskAssignment = (data) => {
    //jwtToken 和 请求类型已做全局拦截添加
    return api({
        url: "/api/TaskAssignment",
        method: "post",
        data
    })
}
//用户新建任务
export const newTask = (data) => {
    //jwtToken 和 请求类型已做全局拦截添加
    return api({
        url: "/api/newTask",
        method: "post",
        data
    })
}

// 获取任务详情
export const getTaskById = (data) => {
    return api({
        url: "/api/AssignedList",
        method: "get",
        data
    })
}

// 管理员更新任务
export const updateTask = (data) => {
    console.log(data);
    let file = new FormData()
    for (let i in data) {
        file.append(i, data[i])
    }
    // const headers = new Headers()
    // headers.append("Content-Type","multipart/form-data")
    return api({
        url: "/api/work/updateAdminWork",
        method: "post",
        data
    })
}
// 用户更新任务
export const userUpdateTask = (data) => {
    // const headers = new Headers()
    // headers.append("Content-Type","multipart/form-data")
    console.log(data);
    let file = new FormData()
    for (let i in data) {
        file.append(i, data[i])
    }
    return api({
        url: "/api/work/updateUserWork",
        method: "post",
        data: file
    })
}

//报表统计管理
export const reportmanagement = (params) => {
    const searchParams = new URLSearchParams();
    if (params.title) searchParams.append('title', params.title);
    if (params.createTime) searchParams.append('createTime', params.createTime);
    if (params.endTime) searchParams.append('endTime', params.endTime);
    return api({
        url: "/api/getReport",
        method: "get",
        params: searchParams,
    })
}

// 密码重置
export const updatePassword = (data) => {
    return api({
        url: "/api/updatePassword",
        method: "post",
        data,
    })
}

// 查询用户个人信息
export const getUserInfo = (userId) => {
    return api({
        url: "/api/UserInfo",
        method: "get",
        params: { userId },
    })
}


//用户首页
export const getAllWorks = (params) => {
    return api({
        url: "/api/work/getAllWorks",
        method: "get",
        params,
    })
}

// 用户管理查询所有用户 (GET)
export const getUserList = () => {
    return api({
        url: "/api/getUserManageInfo",
        method: "get"
    })
}

// 按名字搜索用户 (GET)
export const searchUserByName = (params) => {
    return api({
        url: "/api/getUserManageInfo",
        method: "get",
        params: {
            name: params.name
        }
    })
}

// 查询用户 (GET)
export const searchUser = (params) => {
    console.log('搜索参数:', params);

    return api({
        url: "/api/UserInfo",
        method: "get",
        params: {
            userId: params.userId
        }
    })
}

// 删除单个用户 (POST)
export const deleteUser = (userId) => {
    console.log('删除用户ID:', userId);

    return api({
        url: "/api/users",
        method: "post",
        data: {
            userIds: [userId.toString()]
        }
    })
}

// 批量删除用户 (POST)
export const batchDeleteUsers = (userIds) => {
    console.log('批量删除的用户IDs:', userIds);

    return api({
        url: "/api/users",
        method: "post",
        data: {
            userIds: userIds.map(id => id.toString())
        }
    })
}

// 管理员编辑个人信息
export const editUserInfo = (data) => {
    const token = localStorage.getItem('jwtToken');
    return api({
        url: "/api/editUserInfo",
        method: "post",
        data,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
            'jwtToken': token
        }
    })
}

// 用户 获取全部任务
export const worksList = () => {
    return api({
        url: "/api/worksList",
        method: 'get',
    })
}
// 批量删除任务
export const deleteTasks = (data) => {
    //jwtToken 和 请求类型已做全局拦截添加
    return api({
        url: "/api/tasks",
        method: 'post',
        data
    })
}


// 用户 查询指定的任务
export const searchTask = (data) => {
    return api({
        url: "/api/work/SearchTask",
        method: "post",
        data
    })
}

// 注销账号
export const deactivate = () => {
    return api({
        url: "/api/deactivate",
        method: "put"
    })
}

// 下载图片
export const downloadAvatar = (name) => {
    return api({
        url: "/api/common/download",
        method: "get",
        params: { name },
        responseType: 'blob'  // 指定响应类型为blob
    })
}

// 获取用户详细信息
export const getUserDetail = (userId) => {
    return api({
        url: "/api/UserInfo",
        method: "get",
        params: { userId }
    })
}

// 更新用户信息
export const updateUserInfo = (data) => {
    let formData;

    // 检查传入的是否已经是 FormData
    if (data instanceof FormData) {
        formData = data;
    } else {
        // 如果是普通对象，转换为 FormData
        formData = new FormData();

        // 添加基本字段
        if (data.userId) formData.append('userId', data.userId);
        if (data.name) formData.append('name', data.name);
        if (data.roleId) formData.append('roleId', data.roleId);
        if (data.username) formData.append('username', data.username);
        if (data.gender !== undefined) formData.append('gender', data.gender);
        if (data.email) formData.append('email', data.email);

        // 添加生日
        if (data.birthday !== null && data.birthday !== undefined) {
            formData.append('birthday', data.birthday);
        }

        // 添加密码（如果有）
        if (data.password) {
            formData.append('password', data.password);
            if (data.repassword) {
                formData.append('repassword', data.repassword);
            }
        }

        // 添加文件（如果有）
        if (data.file) {
            formData.append('file', data.file);
        }
    }

    // 打印 FormData 内容（调试用）
    for (let pair of formData.entries()) {
        console.log('API中的FormData:', pair[0] + ': ' + pair[1]);
    }

    return api({
        url: "/api/UpdateUserInfo",
        method: "post",
        data: formData,
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    });
};


export const getUserImg = (name) => {
    return api({
        url: "/api/common/download",
        method: "get",
        params: { name },
        responseType: 'blob'  // 指定响应类型为blob
    })
}

// 删除消息
export const deleteMessage = (messageIds) => {
    return api({
        url: "/api/deleteMessage",
        method: "post",
        data: messageIds  // 直接传递消息ID数组，不需要再包装一层数组
    })
}
//消息已读
export const readMessage = (messageIds) => {
    return api({
        url: "/api/readMessage",
        method: "post",
        data: messageIds  // 直接传递消息ID数组，不需要再包装一层数组
    })
}


//消息已读
export const getFile = (fileName) => {
    return api({
        url: "/api/downloadFile",
        method: "get",
        responseType: 'blob', 
        params: {fileName}  // 直接传递消息ID数组，不需要再包装一层数组
    })
}

